import requests
from PyQt5.QtWidgets import QWidget

import global_config
from ui.Set_forget_password_question_window import Set_forget_password_question_window
from window.My_pop_up_warning import My_pop_up_warning


class My_set_forget_password_question_window(QWidget, Set_forget_password_question_window):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle('设置')

        # 用户名
        self.username = ''

        self.pop_up_warning = My_pop_up_warning()
        self.pop_up_success = My_pop_up_warning()

        # 信号与槽
        self.cancel_button_in_security_page.clicked.connect(self.cancel_set_security_question)
        self.confirm_button_in_security_page.clicked.connect(self.attempt_to_set_security_question)

    def set_username(self, username):
        self.username = username

    def cancel_set_security_question(self):
        # 取消之后将设置密保的界面缓存清空
        self.question1.setText('')
        self.answer1.setText('')
        self.question2.setText('')
        self.answer2.setText('')
        self.close()

    def attempt_to_set_security_question(self):
        is_empty = False
        is_error = False
        if self.question1.text() == '' or self.answer1.text() == '' or self.question2.text() == '' or self.answer2.text() == '':
            is_empty = True
            self.pop_up_warning.warning_info_label.setText('设置失败')
            self.pop_up_warning.warning_info_text.setText('密保问题和答案不能为空')
            self.pop_up_warning.show()

        if not is_empty and (len(self.question1.text()) >= 255 or len(self.answer1.text()) >= 255 or len(
                self.question2.text()) >= 255 or len(self.answer2.text()) >= 255):
            self.pop_up_warning.warning_info_label.setText('设置失败')
            self.pop_up_warning.warning_info_text.setText('密保问题和答案长度不能超过255')
            self.pop_up_warning.show()

        if not is_empty and not is_error:
            url = 'http://' + global_config.localhost + ':8000/setSecurity/'
            params = {
                'username': self.username,
                'que1': self.question1.text(),
                'ans1': self.answer1.text(),
                'que2': self.question2.text(),
                'ans2': self.answer2.text()
            }

            result = requests.get(url, params=params).json()
            if result['result'] == 'success':
                self.close()
                self.question1.setText('')
                self.answer1.setText('')
                self.question2.setText('')
                self.answer2.setText('')
                self.pop_up_success.warning_info_label.setText('设置成功')
                self.pop_up_success.warning_info_text.setText('密保已更新')
                self.pop_up_success.show()

    def closeEvent(self, event):
        self.close()
        self.pop_up_warning.close()
